import { RouteLocationNormalized } from 'vue-router'
import { useStore } from '@/store';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ActionTypesNamespaced } from '@/store/modules/permissions/action-types'
import router from '@/router';
import config from '@/config'


const store = useStore()
const whiteList: string[] | undefined = config.routesWhiteList

NProgress.configure({ showSpinner: false })
router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: any) => {
    NProgress.start()
    if (store.state.user.token) {
        if (to.path == '/login') {
            next('/')
        } else {
            if (store.state.permissions.routes.length > 0) {
                next()
            } else {
                const action: ActionTypesNamespaced = "permissions/ACTION_GENERATE_ROUTER"
                await store.dispatch(action)
                store.state.permissions.routes.forEach(
                    (route: any) => {
                        router.addRoute(route)
                    }
                )
                next({ ...to, replace: true })
            }
        }
    } else {
        if (whiteList?.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`)
        }
    }
})

router.afterEach((to: RouteLocationNormalized) => {
    NProgress.done();

    // set page title
    (document as any).title = to.meta.title
})
